package com.company.project.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.User;
import com.company.project.service.UserService;
import com.company.project.utils.RedisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author PengChenXi
 * @since 2020/03/18.
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 通过GET请求,获取user列表
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping
    public Result<PageInfo<User>> list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<User> list = userService.findAll();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 新增user
     * 通过body 传入 JSON
     *
     * @param user
     * @return
     * @Validated 校验参数
     */
    @PostMapping
    public Result<Object> add(@RequestBody @Validated User user) {
        if (StrUtil.hasEmpty(user.getUserName())) {
            log.error("用户名 不能为空");
        }
        String str = user.getUserName();
        //截取字符串
        String strSub1 = StrUtil.sub(str, 2, 3); //strSub1 -> c

        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<Object> delete(@PathVariable Integer id) {
        userService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 修改
     *
     * @param user
     * @return
     */
    @PutMapping
    public Result<Object> update(@RequestBody User user) {
        userService.update(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 查询单条信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> detail(@PathVariable Integer id) {
        User user = userService.findById(id);
        return ResultGenerator.genSuccessResult(user);
    }

    /**
     * Redis 缓存测试
     *
     * @return
     */
    @PostMapping("/redisTest")
    public Result<Object> test() {
        //redis缓存
        RedisUtils.set("testKey", "testValue", 1800L);
        //hutool 工具缓存
        Cache<String, String> fifoCache = CacheUtil.newFIFOCache(3);

        return ResultGenerator.genSuccessResult(RedisUtils.get("testKey"));
    }

    /**
     * 对单个参数进行校验
     */
    @GetMapping("checkSingleParam")
    public Result singleParam(@RequestParam("name") @NotNull(message = "名字不能为空") String name) {
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 多个参数进行校验
     * 关键在 @Validated
     */
    @PostMapping("/checkParam")
    public Result checkParam(@RequestBody @Validated User user) {
        System.out.println(user.toString());
        return ResultGenerator.genSuccessResult();
    }

    /*
     * GET 单个参数校验
     * 当处理GET请求时或只传入少量参数的时候，我们可能不会建一个bean来接收这些参数，就可以像上面这样直接在controller方法的参数中进行校验。
     * 注意：这里一定要在方法所在的controller类上加入@Validated注解，不然没有任何效果。
     */
//    @RestController
//    @Validated
//    public class PingController {
//        @GetMapping("/getUser")
//        public String getUserStr(@NotNull(message = "name 不能为空") String name,
//                                 @Max(value = 99, message = "不能大于99岁") Integer age) {
//            return "name: " + name + " ,age:" + age;
//        }
//    }


}
